import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../views/Home.vue'
import login from '../views/login/index.vue'
import my from '../views/my/index.vue'
import question from '../views/question/index.vue'
import home from '../views/home/index.vue'
import movie from '../views/movie/index.vue'
import nofind from '../views/nofind/index.vue'
import edit from '../views/edit/index.vue'
import article from '../views/article/index.vue'

import { getToken, removeToken } from '../utils/token'
import { Toast } from 'vant'
import { getuserInfo } from '../api/user'
import store from '../store/index'
import search from '../views/search/index.vue'
import result from '../views/result/index.vue'
import student from '../views/student/index.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: login,
    meta: { showTab: false }
  },
  { path: '/my', component: my, meta: { showTab: true, needlogin: true } },
  { path: '/edit', component: edit, meta: { needlogin: true } },
  { path: '/question', component: question, meta: { showTab: true } },
  { path: '/home', component: home, meta: { showTab: true } },
  { path: '/movie', component: movie, meta: { showTab: true } },
  { path: '/', redirect: '/home' },
  { path: '*', component: nofind },
  { path: '/article/:id', name: 'article', component: article },
  { path: '/search', name: 'search', component: search },
  { path: '/result', name: 'result', component: result },
  { path: '/student', name: 'student', component: student }
]

// 处理路由切换的Promise的reject错误
// 吞掉 没有处理的 promise的错误
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 执行之后 阻断后续代码
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes
})

// 导航卫士实现token认证登录跳转功能
router.beforeEach((to, from, next) => {
  // 先判断去的页面是否需要登陆
  if (to.meta.needlogin === undefined) {
    return next()
  }

  // 需要登陆的页面 判断token是否为null是的话就弹窗提示并跳转login页面
  const tokenobj = getToken()
  if (tokenobj === null) {
    Toast.fail('请登录')
    return next({ path: '/login', query: { back: to.path } })
  }
  // 登录判断优化
  if (store.state.userinfo.name) {
    return next()
  }

  getuserInfo()
    .then(res => {
      store.commit('changeinfo', res.data.data)
      return next()
    })
    .catch(res => {
      // 用dir打印错误对象
      console.dir(res)
      if (res.response.status === 401) {
        Toast.fail('请登录')
        removeToken()
        console.clear()
        return next({ path: '/login', query: { back: to.path } })
      }
    })
})

export default router
